package main;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 解决tianshubang.com不能访问www.tianshubang.com/..../xx.woff2的问题
 * 使用该类，相当于在所有的httpResponse头里面加了Access-Control-Allow-Origin
 * 所有，最简单解决CORS问题的方式，就是两步：
 * 1、使用该类
 * 2、在webapp下写一个web.xml，内容如下：
 *
 * <?xml version="1.0" encoding="UTF-8"?>
 * <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 *          xmlns="http://java.sun.com/xml/ns/javaee"
 *           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 *          id="WebApp_ID" version="3.0">
 *
 *     <filter>
 *         <filter-name>CorsFilter</filter-name>
 *         <filter-class>main.CORSFilter</filter-class>
 *     </filter>
 *
 *     <filter-mapping>
 *         <filter-name>CorsFilter</filter-name>
 *         <url-pattern>/*</url-pattern>
 *     </filter-mapping>
 * </web-app>
 */
public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
